package ro.peoplecentric.ctc.common.service.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import ro.peoplecentric.ctc.common.dao.RegionDao;
import ro.peoplecentric.ctc.common.entity.Region;
import ro.peoplecentric.ctc.common.exception.ApplicationException;
import ro.peoplecentric.ctc.common.exception.ConcurrentModificationException;
import ro.peoplecentric.ctc.common.service.RegionService;

/**
 * {@link RegionService} service implementation.
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = {ApplicationException.class, DataAccessException.class})
public class RegionServiceImpl implements RegionService {

    @Resource
    private RegionDao regionDao;

    @SuppressWarnings("unused")
    @PostConstruct
    private void init() {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void saveRegion(Region region) throws ApplicationException {
        regionDao.saveOrUpdate(region);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void deleteRegion(Region region) throws ApplicationException {
//		 regionDao.lockForUpdate(region);TODO the lock makes delete throw org.hibernate.NonUniqueObjectException
        Region dbRegion = regionDao.getById(Region.class, region.getId());

        if (dbRegion == null) {
            //concurent modification exception
            throw new ConcurrentModificationException("The Region[id : " + region.getId() + "] was already deleted");
        }
        regionDao.delete(dbRegion);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<Region> getAll() {
        return regionDao.getAll();
    }

    @Override
    public Region getById(Long id) throws ApplicationException {
        return regionDao.getById(Region.class, id);
    }
}
